package com.ruoyi.employee.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.organization.domain.Organization;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.employee.mapper.EmployeeMapper;
import com.ruoyi.employee.domain.Employee;
import com.ruoyi.employee.service.IEmployeeService;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 员工信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-11
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService 
{
    private static final Logger log = LoggerFactory.getLogger(EmployeeServiceImpl.class);
    
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询员工信息
     * 
     * @param employeeId 员工信息主键
     * @return 员工信息
     */
    @Override
    public Employee selectEmployeeByEmployeeId(Long employeeId)
    {
        return employeeMapper.selectEmployeeByEmployeeId(employeeId);
    }

    /**
     * 查询员工信息列表
     * 
     * @param employee 员工信息
     * @return 员工信息
     */
    @Override
    public List<Employee> selectEmployeeList(Employee employee)
    {
        return employeeMapper.selectEmployeeList(employee);
    }

    /**
     * 新增员工信息
     * 
     * @param employee 员工信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertEmployee(Employee employee)
    {
        // 创建用户对象
        SysUser user = new SysUser();
        user.setUserName(employee.getName());
        user.setNickName(employee.getName());
        user.setPhonenumber(employee.getPhone());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setRoleIds(new Long[]{101L}); // 根据角色ID制定

        // 设置可选字段以满足数据完整性要求
        user.setSex("0"); // 默认性别（例如：0-男，1-女）
        user.setAvatar(""); // 默认头像
        user.setEmail(""); // 默认邮箱
        user.setDeptId(101L); // 默认部门（建议从参数传入或配置中获取）

        // 插入用户
        sysUserService.insertUser(user);
        // 设置user_id字段（关键修改）
        employee.setUserId(user.getUserId()); // 新增字段赋值
        employee.setEmployeeId(user.getUserId());

        // employee.setEmployeeId(IdUtils.fastSimpleUUID());
        employee.setCreateTime(DateUtils.getNowDate());
        return employeeMapper.insertEmployee(employee);
    }

    /**
     * 修改员工信息
     * 
     * @param employee 员工信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateEmployee(Employee employee)
    {
        // 新增：通过user_id获取用户信息
        Long userId = employee.getUserId(); // 使用新增的user_id字段

        // 查询现有用户信息（避免覆盖其他字段）
        SysUser existingUser = sysUserService.selectUserById(employee.getEmployeeId());
        if (existingUser != null) {
            // 字段完整性检查
            if (StringUtils.isEmpty(employee.getName()) || StringUtils.isEmpty(employee.getPhone())) {
                throw new ServiceException("员工姓名和手机号不能为空");
            }
            
            // 更新必要字段
            existingUser.setUserName(employee.getName());
            existingUser.setNickName(employee.getName());
            existingUser.setPhonenumber(employee.getPhone());
            
            // 配置化角色ID（替换硬编码）
            existingUser.setRoleIds(new Long[]{getConfiguredRoleId()});

            log.info("正在更新用户ID: {} 的信息", existingUser.getUserId());
            int updateResult = sysUserService.updateUser(existingUser);
            
            if (updateResult <= 0) {
                log.error("用户信息更新失败，用户ID: {}", existingUser.getUserId());
                throw new ServiceException("用户信息更新失败");
            }
            log.info("用户信息更新成功，用户ID: {}", existingUser.getUserId());
        }

        employee.setUpdateTime(DateUtils.getNowDate());
        return employeeMapper.updateEmployee(employee);
    }
    
    /**
     * 获取配置化的角色ID
     */
    private Long getConfiguredRoleId() {
        // 实际项目中应从配置中心或数据库获取
        return 101L; 
    }

    /**
     * 批量删除员工信息
     * 
     * @param employeeIds 需要删除的员工信息主键
     * @return 结果
     */
    @Override
    public int deleteEmployeeByEmployeeIds(Long[] employeeIds)
    {
        return employeeMapper.deleteEmployeeByEmployeeIds(employeeIds);
    }

    /**
     * 删除员工信息信息
     * 
     * @param employeeId 员工信息主键
     * @return 结果
     */
    @Override
    public int deleteEmployeeByEmployeeId(Long employeeId)
    {
        return employeeMapper.deleteEmployeeByEmployeeId(employeeId);
    }

    /**
     * 根据员工编号查询员工信息
     * @param jobCode
     * @return
     */
    @Override
    public Employee selectEmployeeByCode(String jobCode) {

        return employeeMapper.selectEmployeeByCode(jobCode);
    }

    /**
     * 根据用户ID查询员工信息
     * @param userId
     * @return
     */
    @Override
    public Employee selectEmployeeByUserId(Long userId) {
        // 示例：假设员工表有sys_user_id字段关联系统用户
        return employeeMapper.selectEmployeeByUserId(userId);
    }

    @Override
    public Employee selectEmployeeByPhone(String phone) {
        return employeeMapper.selectEmployeeByPhone(phone);
    }

    /**
     * 修改员工状态
     *
     * @param employee 员工信息
     * @return 结果
     */
    @Override
    public int updateEmployeeStatus(Employee employee)
    {
        return employeeMapper.updateEmployee(employee);
    }



}
